/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.core.model.config.CounterSignPassTypeEnum;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取会签人员详细信息
 */
public class GetCounterSignerOperationalUsersCmd implements Command<Map<String, Object>>, Serializable {

    private String taskId;

    public GetCounterSignerOperationalUsersCmd(String taskId) {
        this.taskId = taskId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> result = new HashMap<>();
        if (taskId == null) {
            return result;
        }
        TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
        if (task == null) {
            return result;
        }
        if (task.isSuspended()) {
            return result;
        }
        ExecutionEntity multiExecutionEntity = task.getExecution();
        ExecutionEntity parentExecutionEntity = multiExecutionEntity.getParent();
        List<String> users = getListVariable(parentExecutionEntity, MultiInstanceActivityBehavior.PROCESSING_USERS_INFO);
        JSONObject processInfo = getJsonObject(parentExecutionEntity, MultiInstanceActivityBehavior.PROCESSING_INFO);

        List<Map<String, String>> usersInfo = new ArrayList<>();

        if (processInfo != null) {
            HashMap<String, String> opinions = (HashMap<String, String>) processInfo.get("opinions");
            for (String userId : users) {
                Map<String, String> userInfo = new HashMap<>();
                if (Strings.isNullOrEmpty(opinions.get(userId))) {
                    userInfo.put("userId", userId);
                    userInfo.put("userName", "");
                    userInfo.put("opinion", "");
                    usersInfo.add(userInfo);
                } else {
                    userInfo.put("userId", userId);
                    userInfo.put("userName", "");
                    userInfo.put("opinion", opinions.get(userId));
                    usersInfo.add(userInfo);
                }
            }
        } else {
            for (String userId : users) {
                Map<String, String> userInfo = new HashMap<>();
                userInfo.put("userId", userId);
                userInfo.put("userName", "");
                userInfo.put("opinion", "");
                usersInfo.add(userInfo);
            }
        }
        result.put("oneBallotUserId", "");
        result.put("principalOpinion", "");
        if (parentExecutionEntity.getVariable(MultiInstanceActivityBehavior.COUNTERSIGN_PASS_TYPE).equals(CounterSignPassTypeEnum.PASS_PRINCIPAL.toString())) {
            String oneBallotUserId = getStringVariable(parentExecutionEntity, MultiInstanceActivityBehavior.PASS_PRINCIPAL);
            String principalOpinion = getStringVariable(parentExecutionEntity, MultiInstanceActivityBehavior.PRINCIPAL_OPINION);
            result.put("oneBallotUserId", oneBallotUserId);
            result.put("principalOpinion", principalOpinion);
        }
        result.put("usersInfo", usersInfo);
        return result;
    }

    protected String getStringVariable(DelegateExecution execution, String variableName) {
        Object value = execution.getVariable(variableName);
        return (String) (value != null ? value : null);
    }

    protected List<String> getListVariable(DelegateExecution execution, String variableName) {
        Object value = execution.getVariable(variableName);
        return (List) (value != null ? value : null);
    }

    protected JSONObject getJsonObject(DelegateExecution execution, String variableName) {
        Object value = execution.getVariable(variableName);
        return (JSONObject) (value != null ? value : null);
    }

}
